#include <iostream>
#include <stdint.h>
#include <fgwrapper.h>
#include <sdlwrap.h>
#include <../SerialPort/serialport.h>
#include <config.h>
#include <windows.h>

// oh scheisse!!!
int stupid_wrapper(void *p)
{
	reinterpret_cast<FgWrapper *>(p)->process2();
	return 0;
}


FgWrapper::FgWrapper(std::string &cfg_name)
	: cfg_name_(cfg_name)
	, fg_(NULL)
	, fcs_(NULL)
	, finish_(false)
	, timeout_(3000)
	, last_time_(GetTickCount())
{
}


FgWrapper::~FgWrapper()
{
	finish_ = true;

	int status;
	sdl::SDL_WaitThread(thread_, &status);
	
	if (fg_ != NULL)
		delete fg_;

	if (fcs_ != NULL)
		delete fcs_;
}


void FgWrapper::init(void)
{
	Config *cfg = new Config(cfg_name_.c_str());
	
	fg_ = cfg->createInterface("fg");
	fgcomm_.setInterface(fg_);
	fgcomm_.setNoiseMap(cfg->getNoiseMap());

	fcs_ = cfg->createInterface("fcs");
	fcscomm_.setInterface(fcs_);
	
	watch_window_ = cfg->getWatchWindowName();
	timeout_ = cfg->getWatchTimeout();
	
	delete cfg;

	thread_ = sdl::SDL_CreateThread(stupid_wrapper, this);
}


bool FgWrapper::process(void)
{
	if (fgcomm_.read())
		fgcomm_.write();

	return isWindowPresent();
}


void FgWrapper::process2(void)
{
	try 
	{
		while (!finish_)
			fcscomm_.doCycle();
	}
	catch (const std::exception &e)
	{
		std::cout << "Error: " << e.what() << std::endl;
		sdl::SDL_Quit();
		exit(-1);
	}
}


bool FgWrapper::isWindowPresent(void)
{
	uint32_t cur_time = GetTickCount();

	if ((uint32_t)(cur_time - last_time_) > timeout_)
	{
		last_time_ = cur_time;
		return (watch_window_ == "") ? true : (FindWindow(NULL, watch_window_.c_str()) != NULL);
	}
	
	return true;
}


